package service

import (
	"com.cyt.yunpay/library/encrypt"
	"com.cyt.yunpay/library/response"
	"encoding/base64"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/os/gtime"
)

// 验证签名
var VerifySign = new(verifySignService)

type verifySignService struct{}

type SignReq struct {
	AppId      int    `v:"app_id@min:1#应用ID不能为空"` // 应用id
	Sign       string `v:"required#签名不能为空"`       // 签名
	BizContent string `v:"required#验签内容不能为空"`     // 内容
}

// 验证签名
func (s *verifySignService) VerifySign(r *ghttp.Request) {
	var apiReq *SignReq
	if err := r.ParseForm(&apiReq); err != nil {
		response.JsonExit(r, 1, err.Error())
	}

	data, err := SercetConfig.GetSercetConfigByAppId(apiReq.AppId);
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	if data == nil {
		response.JsonExit(r, 1, "暂无该应用配置")
	}

	value, _ := base64.StdEncoding.DecodeString(apiReq.Sign)
	result := encrypt.RsaVerifySign([]byte(apiReq.BizContent), value, []byte(data.AppKey))
	if result == false {
		response.JsonExit(r, 1, "签名校验失败")
	}

	BizContent := gjson.New(apiReq.BizContent)
	reqTime := BizContent.Get("timestamp")
	if reqTime == nil {
		response.JsonExit(r, 1, "未填写正确的时间戳")
	}

	currentTime := gtime.Timestamp()
	compareTime := currentTime - gconv.Int64(reqTime)
	if compareTime > 300 { // 请求大于5分钟
		response.JsonExit(r, 1, "时间戳验证时间过长")
	}

	r.Middleware.Next()
}
